package Leo.serviceClient.controller;

import Leo.serviceClient.entity.User;
import Leo.serviceClient.feign.ProviderClient;
import Leo.serviceClient.service.HystrixService;
import com.netflix.hystrix.contrib.javanica.annotation.DefaultProperties;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import com.netflix.hystrix.contrib.javanica.cache.annotation.CacheResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;

@RestController
@RequestMapping("/hystrixDemo")
@DefaultProperties(groupKey = "hystrixCommand")
public class HystrixController {

    @Autowired
    ProviderClient providerClient;

    @Autowired
    HystrixService hystrixService;

    @RequestMapping("/getUser")
//    @CacheResult //启动Hystrix的缓存
//    @HystrixCommand(fallbackMethod = "fallBack")
    User getUser(@RequestParam("userId") String userId) {
        User user = null;
        for (int i = 1; i < 4; i++) {
            System.out.println("第" + i + "次调用服务");
            user = hystrixService.getUserFromSP(userId);
        }
        return user;
    }

    @RequestMapping("/getUsers")
//    @HystrixCommand(fallbackMethod = "usersFallBack")
    Map getUsers(@RequestParam("userId") String userId) {
        Map<String, User> usersFromSP = hystrixService.getUsersFromSP(userId);
        return usersFromSP;
    }

    /**
     * 测试混合查询
     * @param userId
     * @return
     * @throws ExecutionException
     * @throws InterruptedException
     */
    @RequestMapping("/collUser")
    List collUser(@RequestParam("userId") String userId) throws ExecutionException, InterruptedException {
        ArrayList<User> list = new ArrayList<User>();
        Future<User> f1,f2,f3,f4;
        f1 = hystrixService.collapseGetUser(1 + "");
        f2 = hystrixService.collapseGetUser(2 + "");
        f3 = hystrixService.collapseGetUser(3 + "");
        f4 = hystrixService.collapseGetUser(4 + "");
        list.add(f1.get());
        list.add(f2.get());
        list.add(f3.get());
        list.add(f4.get());
        return list;
    }


    User fallBack(String userId) {
        User user = new User();
        user.setUserName("controller层触发fallback");
        user.setUserId(userId);
        return user;
    }

    Map usersFallBack(String userId) {
        User user = new User();
        user.setUserName("controller层触发胖球");
        user.setUserId(userId);
        Map map = new HashMap();
        map.put(userId,user);
        return map;
    }
}
